import React, { useCallback, useEffect, useState } from "react";
import { Modal, Space } from "antd";
import SetNoteModal from "./component/BulReprice";
import PurchaseOrderModal from "./component/PurchaseOrderModal";
import { SearchTreeSelectTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import SelectActions from "@/views/components/SelectActions";
import { getPurchasestatisticsList } from "./service";
import useColumns from "./cloumns";

const soldPurchasePage = () => {
	const [visible, setVisible] = useState(0);
	const [footerDataSource, setFooterDataSource] = useState([]);
	const { defaultColumns } = useColumns({});
	// 接口
	const tableRequest = getPurchasestatisticsList;

	const [columns, setColumns] = useState(defaultColumns);
	const commonHandleClick = status => {
		if (selectedRows.length) {
			setVisible(status);
		} else {
			Modal.info({ centered: true, content: "请先勾选商品" });
		}
	};

	const rowKey = "seq";
	const getRowsByIds = useCallback((list, ids) => {
		// list 中有 children , 拉平处理
		const flatData = [];
		list.forEach(element => {
			flatData.push(element);
			if (element.children) {
				element.children.forEach(item => {
					// 子集
					flatData.push(item);
				});
			}
		});
		return flatData.filter(e => ids.includes(e[rowKey]));
	});

	const tableKey = "soldPurchase1916";
	const { selectedKeys, selectedRows, fetchList, dataSource, query, searchSimpleTableProps } = useTableConfig({
		tableKey,
		rowKey,
		columns,
		tableRequest,
		autoFetch: true,
		hasPagination: true,
		hasQuickSearch: false,
		beforeQuerySearch: false,
		resetSourceData: false,
		columnResize: true,
		hasColsSetting: true,
		hasToggleSearchForm: true,
		getRowsByIds,
		footerDataSource
	});

	const CheckStockAndNoteProps = {
		visible,
		query,
		fetchList,
		checkedIds: selectedKeys,
		checkedRows: selectedRows,
		dataSource,
		handleOk() {},
		handleCancel() {
			setVisible(0);
		}
	};

	useEffect(() => {
		if (dataSource.length > 0) {
			for (let i = 0; i < dataSource.length; i++) {
				dataSource[i].id = i + 1;

				for (let j = 0; j < dataSource[i].children.length; j++) {
					dataSource[i].children[j].sonId = j + 1;
				}
			}
			setFooterDataSource(pre => {
				return [];
			});
		}
	}, [dataSource]);
	const LeftBtns = (
		<Space>
			<SelectActions name="快销采购" onClick={() => commonHandleClick(1)} />
			<SelectActions name="批量改价" onClick={() => commonHandleClick(4)} />
		</Space>
	);
	const RightBtns = <></>;
	return (
		<>
			<SearchTreeSelectTable
				key={tableKey}
				leftBtns={LeftBtns}
				rightBtns={RightBtns}
				mounted={false}
				{...searchSimpleTableProps}
			/>
			{visible == 1 && <PurchaseOrderModal {...CheckStockAndNoteProps} />}
			{visible == 4 && <SetNoteModal {...CheckStockAndNoteProps} />}
		</>
	);
};

export default React.memo(soldPurchasePage, () => {
	return true;
});
